/**
 * 
 */
package com.netflexitysolutions.amazonws.ec2.security;

import java.io.IOException;
import java.util.Properties;

import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.UnsupportedCallbackException;

import org.apache.ws.security.WSPasswordCallback;
import org.springframework.core.io.Resource;

/**
 * @author netflexity
 *
 */
public class ClientKeystorePasswordCallback implements CallbackHandler {
    
    public static final String ORG_APACHE_WS_SECURITY_CRYPTO_MERLIN_KEYSTORE_ALIAS = "org.apache.ws.security.crypto.merlin.keystore.alias";
	public static final String ORG_APACHE_WS_SECURITY_CRYPTO_MERLIN_KEYSTORE_PASSWORD = "org.apache.ws.security.crypto.merlin.keystore.password";
	
	private Properties passwords = new Properties();
    private Resource keyStoreResource;
    
    /**
     * @param keyStoreResource
     * @throws IOException
     */
    public ClientKeystorePasswordCallback(Resource keyStoreResource) throws IOException{
    	passwords.load(keyStoreResource.getInputStream());
    }

    /* (non-Javadoc)
     * @see javax.security.auth.callback.CallbackHandler#handle(javax.security.auth.callback.Callback[])
     */
    public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
        for (int i = 0; i < callbacks.length; i++) {
            WSPasswordCallback pc = (WSPasswordCallback)callbacks[i];
            
            if(passwords.getProperty(ORG_APACHE_WS_SECURITY_CRYPTO_MERLIN_KEYSTORE_ALIAS).equals(pc.getIdentifier())){
	            String pass = passwords.getProperty(ORG_APACHE_WS_SECURITY_CRYPTO_MERLIN_KEYSTORE_PASSWORD);
	            if (pass != null) {
	                pc.setPassword(pass);
	                return;
	            }
            }
        }
    }

	/**
	 * @return the keyStoreResource
	 */
	public Resource getKeyStoreResource() {
		return keyStoreResource;
	}

	/**
	 * @param keyStoreResource the keyStoreResource to set
	 */
	public void setKeyStoreResource(Resource keyStoreResource) {
		this.keyStoreResource = keyStoreResource;
	}
}
